<script lang="ts" setup>
	import { onPageScroll, onReady } from '@dcloudio/uni-app'
	import { useScrollUpdownBottomContent, useWebsocket, useFormat } from '@/hooks'
	import { useSubPage } from './composables'
	import { ref } from 'vue'
	import {
		getDialogueTopicDetail,
		insertChart,
		deleteChart,
		selectChart,
		uploadAudio,
		getChat,
	} from '@/services/api'
	import { onLoad, onShow, onUnload, onHide } from '@dcloudio/uni-app'
	import { BASE_URL } from '@/config'
	import xmContainer from '@/components/xm-container'
	import guideStep from '@/components/xky-guideStep/xky-guideStep'
	const setTitle = ref('')
	const pageId = ref<Number>(0)
	const { style: authInfoScrollStyle, scrollHandle: authInfoScrollHandle } =
		useScrollUpdownBottomContent('up', 80)
	const {
		connectWebSocketComment,
		connectWebSocket,
		handleClickVideo,
		handleCloseVideo,
		base64toJson,
		webSocketSendMp3,
		webSocketSendComment,
		webSocketSend,
		textTranslate,
		handleDebounce,
		toBase64,
	} = useWebsocket()
	const {
		encodeWAV,
		buf2hex,
		hexToString
	} = useFormat()
	const isUnload = ref(false)
	const requestStatus = ref(false)
	const commentText = ref<any>('hi')
	const recordList = ref<Array>([])
	const animation = ref(false)
	const detailObj = ref({})
	const recorderManager = uni.getRecorderManager()
	const innerAudioContext = uni.createInnerAudioContext()
	innerAudioContext.autoplay = true
	const showPopup = ref(false)
	const isAnimation = ref(false)
	const isHasHistory = ref(false)
	const prologue = ref('')
	const allTipsList = ref()
	const tipsList = ref([])
	const curPromptTips = ref()
	const loading = ref(false)
	const frameBufferList = ref([])
	const playIconPng = ref('../../../static/imgs/play-black.png')
	const playWhiteIconPng = ref('../../../static/imgs/play-white.png')
	const playWhiteIconGif = ref('../../../static/imgs/play_white.gif')
	const playIconGif = ref('../../../static/imgs/play_icon.gif')
	const translateBlack = ref('../../../static/imgs/icons/translate_black.png')
	const translateBlue = ref('../../../static/imgs/icons/translate_blue.png')
	const skillsMessage = ref({
		platform: 'gpt',
		messages: [],
	})
	const textValue = ref(false)
	const platform = ref('gpt') // gpt/kimi/qwen/rag
	const handleClose = () => {
		showPopup.value = false
	}
	const showBottomPopup = ref(false)
	const lineArr = ref([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
	const handleNew = () => {
		showBottomPopup.value = true;
		startRecord()
	}
	const handleCancel = () => {
		textValue.value = false
		showBottomPopup.value = false;
		endRecord()
	}
	const handleSave = () => {
		textValue.value = true
		showBottomPopup.value = false;
		endRecord()
	}
	const closePopup = (type: Boolean) => {
		// 组件回调
		console.log(type,"33333")
	}
	const handleClick = (type : string, value : string, index, source) => {
		switch (type) {
			case 'reload':
				handleCloseVideo()
				isAnimation.value = true
				handleDebounce(() => {
					deleteChart(pageId.value).then((res) => {
						const { code, data } = res
						if (code === 0) {
							isAnimation.value = false
							recordList.value = []
							tipsList.value = []
							skillsMessage.value.messages = []
							// setSkills(curPromptTips.value, 'system')

							recordList.value.push({
								type: 1,
								origin: prologue.value,
								result: '',
								filename: '',
								isTranslate: false,
							})
							console.log(prologue.value)
							skillsMessage.value.messages = [
								{
									content: 'Flora, you are the tallest in the family.',
									role: 'system',
								},
								{
									content: prologue.value,
									// content: 'like you!',
									role: 'assistant',
								},
							]
							//将第一语句传给服务端保存
							let params = {
								id: pageId.value,
								chat: prologue.value,
								role: 1,
								star: 0,
								url: '',
							}
							insertChart(params).then((res) => { })
							getChatAiTag()
						}
					})
				}, 500)
				break
			case 'open':
				showPopup.value = true
				break
			case 'send':
				recordList.value.push({
					type: 2,
					origin: value,
					result: '',
					isTranslate: false,
				})
				//将当前的ai回答语句传给服务端保存
				let params = {
					id: pageId.value,
					chat: value,
					role: 2,
					star: 0,
				}
				insertChart(params).then((res) => { })
				tipsList.value = []
				showPopup.value = false
				// setSkills(value, 'user')
				ragSkills(value, 'user')
				break
			case 'close':
				uni.navigateBack()
				break
			case 'play':
				let strValue = value.origin || value.line
				if (![null, undefined, ''].includes(value.audio_url)) {
					recordList.value = recordList.value.map((item, i) => {
						return {
							...item,
							isPlay: i === index,
						}
					})
					handleClickVideo(value.audio_url).then(() => {
						if (source == 1) {
							recordList.value[index].isPlay = false
						}
						if (source == 2) {
							tipsList.value[index].isPlay = false
						}
					})
					return
				}
				webSocketSendMp3(strValue, 'English').then((res) => {
					if (source == 1) {
						recordList.value = recordList.value.map((item, i) => {
							return {
								...item,
								isPlay: i === index,
							}
						})
					}
					if (source == 2) {
						tipsList.value = tipsList.value.map((item, i) => {
							return {
								...item,
								isPlay: i === index,
							}
						})
						// tipsList.value[index].isPlay = true
					}

					let newArr = []
					res.map((item, index) => {
						const arrayBuffer = wx.base64ToArrayBuffer(item)
						const newBuffer = new Uint8Array(arrayBuffer)
						newArr.push(...newBuffer)
					})
					let uint8Array = new Uint8Array(newArr)
					const newUrl = wx.createBufferURL(uint8Array.buffer)
					recordList.value[index].audio_url = newUrl
					handleClickVideo(newUrl).then(() => {
						if (source == 1) {
							recordList.value[index].isPlay = false
						}
						if (source == 2) {
							tipsList.value[index].isPlay = false
						}
					})
				})

				break
			case 'fanyi':
				textTranslate(value)
					.then(
						(res) => {
							tipsList.value[index].translate = res
							tipsList.value[index].isTranslate = true
						},
						() => {
							translateLongTip()
						}
					)
					.catch(() => {
						translateLongTip()
					})
				autoScroll()
				break
		}
	}
	onUnload(() => {
		isUnload.value = true
		handleCloseVideo()
	})
	onHide(() => {
		handleCloseVideo()
	})
	onReady(() => {
		autoScroll()
	})
	onLoad((option : any) => {
		pageId.value = Number(option.id)
		startWatch()
		init()
	})
	const step = {
    name:'workbenchKey',
    guideList: [
        {
            el: '.dialogue-btn', 
            tips: '点击这里，步骤一', 
            style: "border-radius: 8rpx;margin: 0",
            next:"下一步"
        },{
            el: '.tips-box', 
            tips: '点击这里，步骤二', 
            style: "border-radius: 8rpx;margin: 0",
        },{
            el: '.btn',
            tips: '点击这里，步骤三',
            style: "border-radius: 8rpx;margin: 0",
            next:"我知道啦"
        }]
    }
	const autoScroll = () => {
		setTimeout(function () {
			uni.pageScrollTo({
				scrollTop: 10000, // 假设页面很长，滚动到一个很大的值，从而滚动到底部
				duration: 300, // 滚动动画时长，默认300ms
			})
		}, 100)
	}

	const init = async () => {
		const data = await getDetail(pageId.value)
		setTimeout(function () {
			loading.value = true
		}, 500)
		const isNew = await getHistoryChat()
		Promise.all([data, isNew]).then((result) => {
			skillsMessage.value.messages.push(
				{
					content: 'Flora, you are the tallest in the family.',
					role: 'system',
				},
				{
					content: prologue.value,
					// content: 'like you!',
					role: 'assistant',
				}
			)

			// ragSkills(base64toJson(data.tips), 'system')
			recordList.value.push({
				type: 1,
				origin: prologue.value,
				result: '',
				filename: '',
				isTranslate: false,
			})

			//将第一语句传给服务端保存
			let params = {
				id: pageId.value,
				chat: prologue.value,
				role: 1,
				star: 0,
				url: '',
			}
			insertChart(params).then((res) => { })

			// getChatAiTag()
		})
		// return
		// const isNew = await getHistoryChat()
		// Promise.all([data, isNew]).then((result) => {
		//   skillsMessage.value.messages.push({
		//     content: 'Flora, you are the tallest in the family.',
		//     role: 'system',
		//   })
		//   setSkills(base64toJson(data.tips), 'system')
		// })
	}

	// 获取用户历史聊天内容
	const getHistoryChat = () => {
		return new Promise<void>((resolve, reject) => {
			selectChart(pageId.value).then((res) => {
				const { code, data } = res
				if (code === 0) {
					const chatRecord = JSON.parse(data.chatRecord)
					recordList.value = chatRecord.map((item, index) => {
						return {
							type: item.role,
							origin: item.chat,
							rateValue: item.star,
							audio_url: item.audio_url,
						}
					})
					//自动播放ai第一句
					if (recordList.value.length === 1) {
						onplayTitle(recordList.value[0].origin, 'English')
					}

					//如果有历史记录，加入历史聊天记录上下文到参数
					skillsMessage.value.messages.push({
						content: curPromptTips.value,
						role: 'system',
					})
					skillsMessage.value.messages.push({
						content: 'Hello',
						role: 'user',
					})
					recordList.value.forEach((item, index) => {
						skillsMessage.value.messages.push({
							content: item.origin,
							role: item.type == 1 ? 'assistant' : item.type == 2 ? 'user' : '',
						})
					})
					//获取三个问题对话参考
					// getChatAiTag(recordList.value[recordList.value.length - 1].origin)
				} else if (code != 0) {
					resolve()
				}
			})
		})
	}

	const translateLongTip = () => {
		uni.showToast({
			title: '翻译内容超长',
			duration: 2000,
			icon: 'none',
		})
	}

	// AI进行翻译
	const handleFanyi = (value : string, index : number, rag : string) => {
		textTranslate(value)
			.then(
				(res) => {
					recordList.value[index].result = res
					recordList.value[index].isTranslate = true
				},
				() => {
					translateLongTip()
				}
			)
			.catch(() => {
				translateLongTip()
			})
		// rag
		textTranslate(rag)
			.then(
				(res) => {
					recordList.value[index].ragResult = res
				},
				() => {
					// translateLongTip()
				}
			)
			.catch(() => {
				translateLongTip()
			})
	}
	const setSkills = (res : string, type : string) => {
		let allText = ''
		let resultStr = '' // ai返回的字符串
		if (type == 'system') {
			skillsMessage.value.messages.push({
				content: 'Hello',
				role: 'user',
			})
		}
		recordList.value.push({
			type: 1,
			origin: '',
			result: '',
			filename: '',
			isTranslate: false,
		})
		recordList.value[recordList.value.length - 1].origin =
			'Flora, you are the tallest in the family.'
		return
		const requestTask = uni.request({
			url: `${BASE_URL}/enteacher/aichat`,
			timeout: 15000,
			responseType: 'text',
			method: 'POST',
			enableChunked: true,
			data: skillsMessage.value,
			success: (response) => {
				skillsMessage.value.messages.push({
					content: resultStr,
					role: 'assistant',
				})
				//自动播放ai回答的内容
				onplayTitle(resultStr, 'English')
				setTimeout(() => {
					// getChatAiTag(resultStr)
				}, 1300)
				//将当前的ai回答语句传给服务端保存
				let params = {
					id: pageId.value,
					chat: platform.value == 'qwen' ? allTipsList.value.text : resultStr,
					role: 1,
					star: 0,
					url: '',
				}
				insertChart(params).then((res) => { })
			},
			fail: (error) => { },
		})
		requestTask.onChunkReceived(async function (res) {
			const data16 = buf2hex(res.data) // ArrayBuffer转16进制
			const text = hexToString(data16) // 16进制转字符串
			switch (platform.value) {
				case 'qwen':
					if (text.indexOf(':HTTP_STATUS/200') != -1) {
						let object = JSON.parse(text.split('data:')[1])
						allTipsList.value = JSON.parse(text.split('data:')[1]).output
						let data = []
						recordList.value[recordList.value.length - 1].origin =
							allTipsList.value.text
					}
					break
				case 'kimi':
					let dataArr = text.split('data:')
					let str = ''
					dataArr.map((item) => {
						if (item != '' && item.indexOf('[DONE]') != 1) {
							let obj = JSON.parse(item)
							str += ![null, undefined, ''].includes(obj.choices[0].delta.content)
								? obj.choices[0].delta.content
								: ''
							recordList.value[recordList.value.length - 1].origin += ![
								null,
								undefined,
								'',
							].includes(obj.choices[0].delta.content)
								? obj.choices[0].delta.content
								: ''
						}
					})
					allTipsList.value = str
					break

				case 'gpt':
					let gptStr = ''
					// let newGptStr = ''
					// let dataArrGpt = text.split('data:')
					// let newLc = text.split('{"delta":{"content":"')
					// newLc.shift()
					// newLc.map((item,index) =>{
					// 	gptStr += item.split('"}')[0]
					// })
					// resultStr += gptStr;
					// let index = 0
					// // recordList.value[recordList.value.length - 1].origin = resultStr
					// let gptStrArr = gptStr.split(' ')
					// const streamOutput = () => {
					// 	if (index < gptStrArr.length) {
					// 		let currentText = gptStrArr[index]
					// 		index++
					// 		recordList.value[recordList.value.length - 1].origin += ' ' + currentText
					// 	} else {
					// 		clearInterval(timer)
					// 	}
					// }
					// let timer = setInterval(streamOutput, 30)
					// return;
					allText += text
					if (allText.indexOf('[DONE]') != -1) {
						let dataArrGpt = allText.split('data:')
						dataArrGpt.map((item, index) => {
							if (item != '' && item.indexOf('[DONE]') == -1) {
								let obj = JSON.parse(item)
								gptStr += ![undefined].includes(obj.choices[0].delta.content)
									? obj.choices[0].delta.content
									: ''
							}
						})
						resultStr = gptStr
						let index = 0
						const streamOutput = () => {
							if (index < gptStr.length) {
								let currentText = gptStr.substring(0, index + 1)
								index++
								recordList.value[recordList.value.length - 1].origin = currentText
							} else {
								clearInterval(timer)
							}
						}
						let timer = setInterval(streamOutput, 30)
						// RAG代码
						let ragList = await ragSkills(res, type)
						recordList.value[recordList.value.length - 1].origin = ragList[0]
						break
					}
			}

			autoScroll()
		})
	}
	const ragSkills = (res : string, type : string) => {
		if (type == 'system') {
			skillsMessage.value.messages.push({
				content: 'what do you like?',
				role: 'user',
			})
		}
		if (type == 'user') {
			skillsMessage.value.messages.push({
				content: res,
				role: 'user',
			})
		}
		let obj = {
			...skillsMessage.value,
			platform: 'rag',
			type: 1,
			area: `1_${detailObj.value.grade}_${detailObj.value.topicEnglish}`,
		}
		return new Promise((resolve, reject) => {
			getChat(obj).then((res) => {
				const { code, data, msg } = res
				if (code === 0) {
					let resultStr = data[0]
					recordList.value.push({
						type: 1,
						origin: resultStr,
						result: '',
						filename: '',
						isTranslate: false,
					})
					skillsMessage.value.messages.push({
						content: resultStr,
						role: 'assistant',
					})
					//自动播放ai回答的内容
					onplayTitle(resultStr, 'English')
					setTimeout(() => {
						// getChatAiTag(resultStr)
					}, 1300)
					//将当前的ai回答语句传给服务端保存
					let params = {
						id: pageId.value,
						chat: resultStr,
						role: 1,
						star: 0,
						url: '',
					}
					insertChart(params).then((res) => { })
					resolve(data)
					autoScroll()
				} else {
					uni.showToast({
						title: msg,
						duration: 2000,
						icon: 'none',
					})
					resolve(['rag没返回'])
				}
			})
		})
	}
	// 获取对话参考
	const getChatAiTag = async (value : string) => {
		let obj = {
			platform: 'rag',
			messages: skillsMessage.value.messages,
			type: 3,
			area: `1_${detailObj.value.grade}_${detailObj.value.topicEnglish}`,
			// area: `1_3_Just like you`,
		}
		// RAG代码
		const { code, data, msg } = await getChat(obj)
		if (code === 0) {
			tipsList.value = data.map((item) => {
				return { line: item }
			})
		} else {
			uni.showToast({
				title: msg,
				duration: 2000,
				icon: 'none',
			})
		}
		return
		let allText = ''
		let messageData = {
			platform: platform.value,
			messages: [
				{
					content: `Role:中国小学英语老师 Profile: - author: 中国小学英语老师 - version: 0.1 - language: 英文 - description: 你是一个中国小学一年级的英语老师，擅长跟你的学生进行简单的场景对话，帮助你的学生在特定的场景下学习英文口语。 Rules: - 根据给定的对话主题<Scene>，你先对学生发起对话。 -在整个对话中，你每次发起一个提问，都讲根据对话的上下文提供3个参考回答 --每个回答的字数在100token以内 -- 回答的范围和内容过程中，涉及到的单词包含在<Words>中，请不要使用超过<Words>中的单词 Scene： - 对话的主题是《见面问候》 - 对话的主旨的让学生能够说出各种学习用品的英语单词 Words： -Good morning / afternoon / evening -How are you? -I'm fine, thank you. 。 -Nice to meet you. -What's your name? -My name is [Name]. -Goodbye / Bye -Thank you / Thanks -You're welcome. -Please -Sorry -Excuse me -Hello, everyone!" −What's this? −This is a ... . −How many ... do you have? - −I have ... −Do you have a ...? −Yes, I do. / No, I don't. −Show me your ...`,
					role: 'system',
				},
				...skillsMessage.value.messages.slice(1),
				{
					content:
						' 根据对话的上下文提供3个参考答案' +
						value +
						'这句话,请按照此JSON格式输出 [{"line"\:"one"\},{"line"\:"two"\},{"line"\:"three"\}] 不允许返回与此格式无关的内容,不允许返回中文，只可以英文回复',
					role: 'user',
				},
			],
		}
		let str = ''
		const requestTask = uni.request({
			url: `${BASE_URL}/enteacher/aichat`,
			timeout: 15000,
			responseType: 'text',
			method: 'POST',
			enableChunked: true,
			data: messageData,
			success: (response) => { },
			fail: (error) => { },
		})
		requestTask.onChunkReceived(function (res) {
			const uint8Array = new Uint8Array(res.data)
			let text = String.fromCharCode.apply(null, uint8Array)
			switch (platform.value) {
				case 'qwen':
					if (text.indexOf(':HTTP_STATUS/200') != -1) {
						if (text.indexOf('```json') != -1) {
							let obj = text.split('```json')[1].split('```')[0]
							let newStr = obj.replace(/\\n/g, '').replace(/\\/g, '')
							let newData = JSON.parse(newStr)
							tipsList.value = newData
							tipsList.value.forEach((item) => {
								item.isPlay = false
							})
						} else {
							let data = text.split('data:')[1]
							tipsList.value = JSON.parse(JSON.parse(data).output.text)
							tipsList.value.forEach((item) => {
								item.isPlay = false
							})
						}
					}
					break
				case 'kimi':
					let dataArr = text.split('data:')
					dataArr.map((item) => {
						if (item != '' && item.indexOf('[DONE]') != 1) {
							let obj = JSON.parse(item)
							str += ![undefined].includes(obj.choices[0].delta.content)
								? obj.choices[0].delta.content
								: ''
						}
						if (item.indexOf('[DONE]') == 1) {
							if (str.indexOf('```json') != -1) {
								let obj = str.split('```json')[1].split('```')[0]
								tipsList.value = JSON.parse(obj)
							} else {
								tipsList.value = JSON.parse(str)
							}
						}
					})
					break
				case 'gpt':
					allText += text
					if (allText.indexOf('[DONE]') != -1) {
						let dataArrGpt = allText.split('data:')
						dataArrGpt.map((item, index) => {
							if (item != '' && item.indexOf('[DONE]') == -1) {
								let obj = JSON.parse(item)
								str += ![undefined].includes(obj.choices[0].delta.content)
									? obj.choices[0].delta.content
									: ''
							}
						})
						tipsList.value = JSON.parse(str)
					}
					break
			}
		})
	}
	const getUserMp3 = () => {
		return new Promise<void>((resolve, reject) => {
			let newArr = []
			frameBufferList.value.map((item, index) => {
				const newBuffer = new Uint8Array(item)
				newArr.push(...newBuffer)
			})
			const uint8Array = new Uint8Array(newArr)
			let view = encodeWAV(uint8Array.buffer, 1, 16000)
			let baseData = toBase64(view.buffer, 'normal')
			let fileName = new Date().getTime()
			let obj = {
				file_name: fileName + '.wav',
				base64_file: baseData, // Base64 编码的文件内容
				project_name: 'userMp3',
			}
			uploadAudio(obj).then((res) => {
				const { message, data } = res
				if (message === 'pong') {
					resolve(data.fileUrl)
				} else {
					frameBufferList.value = []
					reject({ code: '400', msg: '未返回图片' })
				}
			})
		})
	}
	// 长按录制
	const startRecord = () => {
		handleCloseVideo()
		animation.value = true
		connectWebSocket().then(async (res : string) => {
			let path = await getUserMp3()
			if (res != '' && textValue.value == true) {
				recordList.value.push({
					type: 2,
					origin: res,
					result: '',
					filename: '',
					rateValue: '',
					isTranslate: false,
					audio_url: path,
				})
				autoScroll()
				//将当前的ai回答语句传给服务端保存
				let params = {
					id: pageId.value,
					chat: res,
					role: 2,
					audio_url: path,
				}
				insertChart(params).then((res) => { })
				ragSkills(res, 'user')
				frameBufferList.value = []
			} else if (res == '' && textValue.value == true) {
				uni.showToast({
					title: '未识别到文字',
					icon: 'none',
				})
				frameBufferList.value = []
			}
			textValue.value = false
		})
		recorderManager.start({
			duration: 30000, // 600000（10 分钟）,默认值 60000（1 分钟）
			numberOfChannels: 1, // 录音通道数，有效值 1/2
			frameSize: 8,
			format: 'pcm', // 音频格式
			sampleRate: 16000, // 采样率
		})
	}
	// 松开停止
	const endRecord = () => {
		animation.value = false
		recorderManager.stop()
	}
	const startWatch = () => {
		var lastFrame = []
		recorderManager.onStop(function (res) {
			// 监听最后一帧
			webSocketSend(lastFrame, true).then((res) => {
				if (res == 'success') {
				}
			})
			lineArr.value = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
			let tempFile = res.tempFilePath //音频文件地址
			// #ifdef MP-WEIXIN
			const fs = uni.getFileSystemManager()
			// 评分
			fs.readFile({
				// 拿到用户自己录制的音频保存
				filePath: tempFile,
				success: (res) => { },
			})
			// #endif
		})
		recorderManager.onFrameRecorded(function (res) {
			const { frameBuffer, isLastFrame } = res
			frameBufferList.value.push(frameBuffer)
			lastFrame = frameBuffer
			// 基础
			webSocketSend(frameBuffer, isLastFrame).then((res) => {
				if (res == 'success') {
				}
			})
			const intArray = new Int16Array(frameBuffer)
			// 到这一步还能理解，但是 intArray 返回的切片数据太多，才疏学浅没有明白里面具体代表的含义，百度也找了很久没什么资料可以参考，最后找规律发现在每一条的最大值基本代表了现在的振幅，所以直接一步到位取了个最大值，有懂的朋友可以不吝赐教一下
			const amplitude = Math.max(...intArray) // 计算当前帧的振幅
			// 最后将每次的振幅保存下来，进行绘制即可 ， 3276.8 是 根据 采样率及编码码率及你的波形图的最高高度得出的一个合适值， 这个可以随便试一试就出来了
			lineArr.value.push(amplitude / 3276.8)
			lineArr.value.shift()
		})
	}
	const getDetail = (id) => {
		return new Promise<void>((resolve, reject) => {
			getDialogueTopicDetail({ id: id }).then((res) => {
				const { code, data } = res
				if (code === 0) {
					setTitle.value = data.topicChinese
					uni.setNavigationBarTitle({
						title: setTitle.value, // 可以根据需要设置为任意字符串
					})
					// console.log(JSON.str,"skillsMessage.valueskillsMessage.value")
					curPromptTips.value = base64toJson(data.tips)
					prologue.value = data.prologue
					detailObj.value = data
					resolve(data)
				}
			})
		})
	}
	const onplayTitle = async (value, type) => {
		if (!isUnload.value) {
			// Chinese中文 | English英文
			let res = await webSocketSendMp3(value, type)
			let newArr : any = []
			res.map((item, index) => {
				const arrayBuffer = wx.base64ToArrayBuffer(item)
				const newBuffer = new Uint8Array(arrayBuffer)
				newArr.push(...newBuffer)
			})
			let uint8Array = new Uint8Array(newArr)
			const newUrl : any = wx.createBufferURL(uint8Array.buffer)
			if (!isUnload.value) {
				handleClickVideo(newUrl)
			}
		}
	}
	onPageScroll((e) => { })
</script>

<template>
	<xm-container :loading="loading">
		<template v-slot="{ message }">
			<view class="top-bg" />
			<!-- 内容 -->
			<view class="page">
				<view class="dialogue-btn font-size-14 font-color-white flex flex-ai-center flex-js-center">
					话题：{{detailObj.topicEnglish}} {{detailObj.topicChinese}}</view>
				<view @click="handleClick('reload')" class="flex flex-ai-center flex-js-end mt-5  pr-15"
					:class="isAnimation ? 'active-btn-item' : 'btn-item'">
					<TnIcon name="refresh" size="50" />
					<text class="font-size-12 ml-4">重新对话</text>
				</view>
				<!-- 内容部分 -->
				<scroll-view class="tn-text-justify" style="padding-bottom: 180rpx" scroll-top="10000">
					<view class="mlr-15" v-for="(item, index) in recordList" :key="index">
						<view class="tn-flex tn-flex-row-between tn-flex-col-center" v-if="item.type == 1">
							<view class="justify-content-item">
								<view class="tn-flex tn-flex-col-top tn-flex-row-left">
									<view class="tn-padding-right tn-color-black">
										<view class="tn-flex tn-flex-col-center">
											<view class="tn-margin-sm tn-padding-sm tn-bg-white" style="
                          max-width: 62vw;
                          border-radius: 0 20rpx 20rpx 20rpx;
                        ">
												<view class="flex flex-js-sb">
													<view class="mr-4 origin-box" style="min-width: 120rpx">
														<view v-if="item.origin">{{ item.origin }} </view>
														<view v-else class="loader-40"></view>
													</view>
													<image v-if="item.origin"
														style="display: inline-table; flex-shrink: 0"
														class="radius-50 pngStyle"
														:class="item.isPlay ? 'is-translate' : ''"
														:src="item.isPlay ? playIconGif : playIconPng"
														@click="handleClick('play', item, index, 1)"></image>
												</view>
												<view v-if="item.result">
													<view class="line mtb-8" style="border-bottom: 1rpx solid #dcdcdc">
													</view>
													<view class="tn-color-black bg-color-white"
														style="max-width: 450rpx">
														<view>{{ item.result }} </view>
														<!-- 	<view style="color:blue"><text
																class="font-w-600 mr-5">rag:</text>{{ item.ragResult }}
														</view> -->
													</view>
												</view>
											</view>
											<view class="" v-if="item.origin">
												<image style="width: 40rpx; height: 40rpx"
													:class="item.isTranslate ? 'is-translate' : ''" :src="
                            item.isTranslate ? translateBlue : translateBlack
                          " @click="handleFanyi(item.origin, index, item.rag)">
												</image>
											</view>
										</view>
									</view>
								</view>
							</view>
							<view class="justify-content-item"></view>
						</view>
						<view class="tn-flex tn-flex-row-between tn-flex-col-center" v-if="item.type == 2">
							<view class="justify-content-item"></view>
							<view class="justify-content-item">
								<view class="tn-flex tn-flex-col-top tn-flex-row-left">
									<view class="tn-padding-left tn-color-black">
										<view class="tn-flex tn-flex-col-center">
											<image style="width: 40rpx; height: 40rpx"
												:class="item.isTranslate ? 'is-translate' : ''"
												:src="item.isTranslate ? translateBlue : translateBlack"
												@click="handleFanyi(item.origin, index)"></image>
											<view class="tn-margin-sm tn-padding-sm f-color-text flex flex-ai-center"
												style="max-width: 62vw">
												<view>
													<view class="flex flex-js-sb">
														<view class="mr-4 origin-box" style="max-width: 380rpx">
															{{ item.origin }}
														</view>
														<image class="radius-50 pngStyle"
															:class="item.isPlay ? 'is-translate' : ''" :src="
                                item.isPlay
                                  ? playWhiteIconGif
                                  : playWhiteIconPng
                              " @click="handleClick('play', item, index, 1)"></image>
													</view>
													<view v-if="item.result">
														<view class="line mtb-8"
															style="border-bottom: 1rpx solid #dcdcdc">
														</view>
														<view class="tn-color-white" style="max-width: 450rpx">
															{{ item.result }}
														</view>
													</view>
													<TnRate v-show="item.rateValue != ''" v-model="item.rateValue"
														active-color="#FAC909" :min="0" :max="5" allow-half
														:readonly="true" style="float: right; margin-top: 18rpx" />
												</view>
											</view>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
					<!-- 提示布局 -->
					<view class="tips-box pa-12">
						<view>
							<view class="font-color-ce99d42 font-size-14 font-w-600">您的对话已经偏离当前话题“开学”</view>
							<view class="font-color-ce99d42 mt-4">Your conversation has strayed from the current topic
								"Starter"</view>
						</view>
						<view class="mtb-8 tips-line"></view>
						<view class="tips-text flex flex-ai-center">
							<image class="tips-text_img"
								src="http://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/hr-wechat/static/tips-expert.png"
								mode=""></image>
							<text class="ml-4 font-size-16 font-w-600" style="color: #2ad100;">你可以这样说：</text>
						</view>
						<view class="tips-list">
							<view class="list mt-12" v-for="(item,index) in 2">
								<view class="flex flex-ai-center">
									<view class="line"></view>
									<view class="ml-4">Hi, Miss Zhang! I'm Lily.</view>
									<image class="ml-4 image" :src="playIconPng" mode=""></image>
								</view>
								<view class="mt-2">嗨，张老师！我叫莉莉。</view>
							</view>
						</view>
					</view>
				</scroll-view>
				<TnPopup v-model="showBottomPopup" open-direction="bottom" :radius="150" :overlay="false"
					:overlay-closeable="false" maskCloseable="false" top="54px">
					<view class="footer">
						<view class="recording-gif flex flex-ai-center flex-js-center" style="height: 120rpx;">
							<view class="flex flex-ai-center flex-js-center">
								<view v-for="(item, index) in lineArr" class="mr-6" style="
					        display: inline-table;
					        background: white;
					        width: 20rpx;
					        border-radius: 20rpx;
					      " :style="{ height: 20 + item * 15 + 'rpx' }"></view>
							</view>
						</view>
						<view class="flex">
							<view class="footer-btn" @click="handleCancel">
								<view class="footer-btn-active flex flex-ai-center flex-js-center"
									style="background: white;">
									<TnIcon name="close" size="50" />
								</view>
								<view class="font-color-c333 mt-4">取消</view>
							</view>
							<view class="footer-btn" @click="handleSave">
								<view class="footer-btn-active flex flex-ai-center flex-js-center">
									<TnIcon name="send" color="#ffffff" size="50" />
								</view>
								<view class="font-color-c4B49E8 mt-4">发送</view>
							</view>
						</view>
					</view>
				</TnPopup>
				<view class="footer-show flex flex-js-center">
					<view class="btn mt-10 flex flex-ai-center flex-js-center" @click="handleNew">
						<TnIcon name="refresh" size="50" />
						<text class="ml-4">点击开始对话</text>
					</view>
				</view>
			</view>
			<!-- 提示答案 -->
			<TnPopup v-model="showPopup" class="popup-box" open-direction="bottom" :radius="30" top="54px">
				<view class="plr-16 popup-main">
					<view class="popup-title flex flex-js-sb flex-ai-center">
						<view></view>
						<view class="font-size-16 font-color-c333 font-w-bold">你可以这样说</view>
						<image class="close-icon" src="../../../static/imgs/close.png" @click="handleClose"></image>
					</view>
					<view class="popup-contnet mt-6">
						<view style="text-align: center" class="mt-40" v-if="tipsList.length == 0">
							<view class="loader">
								<view class="circle loading1"></view>
								<view class="circle loading2"></view>
								<view class="circle loading3"></view>
								<view class="circle loading4"></view>
								<view class="circle loading5"></view>
								<view class="circle loading6"></view>
								<view class="circle loading7"></view>
								<view class="circle loading8"></view>
							</view>
							<view class="mt-12 loader-text">加载中，请稍等</view>
						</view>
						<view v-else>
							<view class="flex-1 flex items pa-12 br-16 flex-js-sb mb-12 bg-color-white"
								v-for="(item, index) in tipsList" :key="index">
								<view class="">
									<view class="flex">
										<view class="mr-8 items-line" @click="handleClick('send', item.line)">
											{{ item.line }}
										</view>
										<view class="flex mt-2">
											<image class="play-icon mr-6" :class="item.isPlay ? 'is-translate' : ''"
												:src="item.isPlay ? playIconGif : playIconPng" mode=""
												@click="handleClick('play', item, index, 2)">
											</image>
											<image class="translate-icon"
												:class="item.isTranslate ? 'is-translate' : ''"
												:src="item.isTranslate ? translateBlue : translateBlack" mode=""
												@click="handleClick('fanyi', item.line, index)"></image>
										</view>
									</view>
									<view class="split-line mtb-8" v-if="item.translate"></view>
									<view class="mt-4" v-if="item.translate">{{
                    item.translate
                  }}</view>
								</view>
							</view>
						</view>
					</view>
					<view class="popup-footer pt-10">
						<view class="footer-btn flex flex-ai-center flex-js-center">
							<image class="icon radius-50" src="../../../static/imgs/index/expert-video.png"
								@touchstart.stop="startRecord" @touchend.stop="endRecord">
							</image>
						</view>
						<view class="font-bold font-size-14 font-color-c191919 mt-4">按住说话</view>
					</view>
				</view>
			</TnPopup>
			<guideStep :step="step"></guideStep>
			<!-- 历史记录  -->
			<!-- <xm-toast show='true' showBtnType="2" cancelText="继续对话" submitText="重新对话" title="提示" content="你有历史学习记录，请选择是否继续对话？"></xm-toast> -->
			<!-- 学习完成 -->
			<!-- <xm-toast show='true' showBtnType="2" cancelText="重新对话" submitText="返回目录" title="学习完成" content="恭喜你完成了本话题的达人对话练习！" @closePopup="closePopup"></xm-toast> -->
		</template>
	</xm-container>
</template>

<style lang="scss" scoped>
	@import './styles/index.scss';

	.pngStyle {
		width: 40rpx;
		height: 40rpx;
	}

	.refish {
		transition: 1s;
		transform: rotate(360deg);
	}

	.origin-box {
		word-wrap: wrap;
		text-align: left;
		// word-break: break-all;
	}

	.btn-box {
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;
		width: 200rpx;

		.iconBox {
			width: 72rpx;
			height: 72rpx;
			background: #ffffff;
			box-shadow: 0rpx 8rpx 8rpx 0rpx #f8f8f8;
			border-radius: 50%;
			display: flex;
			justify-content: center;
			align-items: center;
		}

		.active-iconBox {
			width: 100rpx;
			height: 100rpx;
			background: linear-gradient(90deg, #4b49e8 0%, #6b8bfb 100%);
			box-shadow: 0rpx 8rpx 8rpx 0rpx #f8f8f8;
			border-radius: 50%;
			display: flex;
			justify-content: center;
			align-items: center;
		}

		.refish {
			transition: 1s;
			transform: rotate(360deg);
		}

		.btn-item {
			font-weight: 400;
			font-size: 24rpx;
			color: #666666;
			line-height: 28rpx;
			margin-top: 12rpx;
		}

		.active-btn-item {
			color: #191919;
			font-weight: 400;
			font-size: 24rpx;
			line-height: 28rpx;
			margin-top: 20rpx;
		}
	}

	.is-translate {
		animation: btnSpin 0.2s 0s 1;
		color: red;
	}

	@keyframes btnSpin {
		0% {
			scale: 0.8;
		}

		25% {
			scale: 1;
		}

		50% {
			scale: 1.2;
		}

		75% {
			scale: 1;
		}

		100% {
			scale: 0.8;
		}
	}

	.loader-40 {
		width: 24rpx;
		height: 24rpx;
		border-radius: 50%;
		display: inline-block;
		position: relative;
		background: #fff;
		box-shadow:
			-40rpx 0 #e8e8ff,
			40rpx 0 #e8e8ff;
		animation: shadowPulse 2s linear infinite;
		margin-left: 45rpx;
	}

	@keyframes shadowPulse {
		33% {
			background: #e8e8ff;
			box-shadow:
				-40rpx 0 #4b49e8,
				40rpx 0 #e8e8ff;
		}

		66% {
			background: #4b49e8;
			box-shadow:
				-40rpx 0 #e8e8ff,
				40rpx 0 #e8e8ff;
		}

		100% {
			background: #e8e8ff;
			box-shadow:
				-40rpx 0 #e8e8ff,
				40rpx 0 #4b49e8;
		}
	}
</style>